package com.text.mqtt_text.mqtt;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class ChatMessage {
    public static void Message() {
        try {
            String token = "Bearer eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjIyODUzOCwidXNlcm5hbWUiOiIrODYxMzI3MzA1NzI1MyIsInRlbGVwaG9uZSI6Iis4NjEzMioqKio3MjUzIiwicm9sZSI6InVzZXIiLCJpYXQiOjE3NTUxNDA0MDYsImV4cCI6MTc2MjkxNjQwNn0.ao7KRGOWk0A9wj4qQhvJyyUBhaPjPi9YdBwE1jwH-tq3E0gf6Pz9KbgDrQqeAjImMbNg8LvhYp7cM67K8_KMDw";
            String chatListUrl = "https://xiaozhi.me/api/agents/170573/chats";

            // 1. 获取所有聊天id
            JSONArray chatIds = new JSONArray();
            {
                HttpURLConnection con = (HttpURLConnection) new URL(chatListUrl).openConnection();
                con.setRequestMethod("GET");
                con.setRequestProperty("User-Agent", "Mozilla/5.0");
                con.setRequestProperty("Authorization", token);

                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
                StringBuilder response = new StringBuilder();
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                JSONObject json = new JSONObject(response.toString());
                JSONArray dataArr = json.getJSONArray("data");
                for (int i = 0; i < dataArr.length(); i++) {
                    chatIds.put(dataArr.getJSONObject(i).getLong("id"));
                }
            }

            // 2. 轮询每个聊天id，获取消息，全部放到List
            List<JSONObject> allMessages = new ArrayList<>();
            for (int i = 0; i < chatIds.length(); i++) {
                long chatId = chatIds.getLong(i);
                String msgUrl = "https://xiaozhi.me/api/agents/170573/chats/" + chatId + "/messages";
                try {
                    HttpURLConnection con = (HttpURLConnection) new URL(msgUrl).openConnection();
                    con.setRequestMethod("GET");
                    con.setRequestProperty("User-Agent", "Mozilla/5.0");
                    con.setRequestProperty("Authorization", token);

                    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
                    StringBuilder response = new StringBuilder();
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();

                    JSONObject json = new JSONObject(response.toString());
                    if (!json.has("data")) continue;
                    JSONArray dataArr = json.getJSONArray("data");
                    for (int j = 0; j < dataArr.length(); j++) {
                        JSONObject item = dataArr.getJSONObject(j);
                        JSONObject filtered = new JSONObject();
                        filtered.put("content", item.optString("content", ""));
                        filtered.put("role", item.optString("role", ""));
                        filtered.put("created_at", item.optString("created_at", ""));
                        allMessages.add(filtered);
                    }
                } catch (Exception e) {
                    System.out.println("获取聊天ID " + chatId + " 的消息失败：" + e.getMessage());
                }
            }

            // 3. 按created_at排序
            allMessages.sort(Comparator.comparing(o -> Instant.parse(o.optString("created_at", "1970-01-01T00:00:00.000Z"))));

            // 4. 合并并保存
            JSONArray sortedArr = new JSONArray();
            for (JSONObject obj : allMessages) {
                sortedArr.put(obj);
            }
            JSONObject result = new JSONObject();
            result.put("data", sortedArr);

            String filePath = "downloaded_configs/chatmassage.txt";
            try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"))) {
                writer.write(result.toString(2));
            }

            System.out.println("已保存到: " + filePath);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}